<!-- src/components/CommentItem.vue -->
<script setup>
import { ref,defineProps,defineEmits } from 'vue';
import { useRoute } from 'vue-router';
import request from '../axios/request';
import { ElMessage } from 'element-plus';


const props = defineProps({
  comment: Object,
  comments: Array,
  currentUser: Object,
});

const emit = defineEmits(['delete-comment', 'show-reply']);

const route = useRoute();
const replyContent = ref('');
const replyFormVisible = ref(false);

const formatDate = (date) => {
  return new Date(date).toLocaleString();
};

const pageKey = ref(sessionStorage.getItem('pageKey') || `${route.path || '/game'}-${Math.random().toString(36).substr(2, 9)}`);

const getReplies = (parentId) => props.comments.filter(comment => comment.parentId === parentId);

const submitReply = async (parentId) => {
  if (!props.currentUser) {
    ElMessage.error('请先登录');
    return;
  }
  try {
    const res = await request({
      url: '/comments/add',
      method: 'post',
      data: {
        userId: props.currentUser.id,
        gameId: route.params.id,
        content: replyContent.value,
        parentId: parentId
      },
      pageKey: pageKey.value,
    });
    if (res.data.code === 200) {
      ElMessage.success('回复发布成功');
      replyContent.value = '';
      replyFormVisible.value = false;
      emit('show-reply', null); // 触发 show-reply 事件

    } else {
      console.error('评论发布失败:', res.data.msg);
      ElMessage.error('评论发布失败');
    }
  } catch (err) {
    console.error('发布评论失败:', err);
    ElMessage.error('请求失败，请检查网络');
  }
};

const deleteComment = async (commentId) => {
  if (!props.currentUser) {
    ElMessage.error('请先登录');
    return;
  }
  try {
    const res = await request({
      url: '/comments/delete?commentId='+commentId,
      method: 'delete',
      pageKey: pageKey.value,
    });
    if (res.data.code === 200) {
      ElMessage.success('评论删除成功');
      emit('delete-comment', commentId);
    } else {
      console.error('删除失败:', res.data.msg);
      ElMessage.error('删除失败');
    }
  } catch (err) {
    console.error('删除评论失败:', err);
    ElMessage.error('请求失败，请检查网络');
  }
};

// const fetchComments = async () => {
//   try {
//     const res = await request({
//       url: '/comments/gameComments?gameId='+route.params.id,
//       method: 'post',
//       pageKey: pageKey.value,
//     });
//     if (res.data.code === 200) {
//         emit('update:comments', res.data.data || []); // 触发更新 comments 事件
//     } else {
//       console.error('获取评论失败:', res.data.msg);
//       ElMessage.error('加载评论失败');
//     }
//   } catch (err) {
//     console.error('请求失败:', err);
//     ElMessage.error('请求失败，请检查网络');
//   }
// };
</script>

<template>
  <el-card :class="['comment-item', { 'nested-reply': comment.parentId }]">
    <p>{{ comment.content }}</p>
    <div class="comment-meta">
      <span>用户名称: {{ comment.userName }}</span>
      <span>{{ formatDate(comment.createdAt) }}</span>
      <el-button
        v-if="currentUser"
        type="info"
        size="small"
        @click="replyFormVisible = !replyFormVisible"
      >回复</el-button>
      <el-button
        v-if="currentUser && currentUser.id === comment.userId"
        type="danger"
        size="small"
        @click="deleteComment(comment.id)"
      >删除</el-button>
    </div>
    <div v-if="replyFormVisible" class="reply-form">
      <el-input
        v-model="replyContent"
        type="textarea"
        :rows="2"
        placeholder="请输入回复"
      ></el-input>
      <el-button type="primary" @click="submitReply(comment.id)" :disabled="!replyContent.trim()">提交回复</el-button>
    </div>
    <div class="replies">
      <comment-item
        v-for="reply in getReplies(comment.id)"
        :key="reply.id"
        :comment="reply"
        :comments="comments"
        :current-user="currentUser"
        @delete-comment="$emit('delete-comment', $event)"
        @show-reply="$emit('show-reply', $event)"
      />
    </div>
  </el-card>
</template>

<style scoped>
.comment-item {
  margin-bottom: 15px;
  padding: 15px;
  border-radius: 8px;
  background: #f9f9f9;
  transition: background 0.2s ease;
}

.comment-item:hover {
  background: #f1f1f1;
}

.comment-item p {
  font-size: 1rem;
  color: #34495e;
  margin: 0 0 10px 0;
  line-height: 1.5;
}

.comment-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 0.85rem;
  color: #95a5a6;
  margin-bottom: 10px;
}

.comment-meta .el-button {
  padding: 5px 10px;
  font-size: 0.8rem;
}

.reply-form {
  margin: 10px 0;
  padding: 10px;
  background: #f1f1f1;
  border-radius: 8px;
}

.reply-form .el-input {
  margin-bottom: 10px;
}

.reply-form .el-button {
  width: 100%;
}

.replies {
  margin-top: 10px;
  padding-left: 15px;
  border-left: 3px solid #409EFF !important;
}

.reply-item {
  margin-bottom: 10px;
  padding: 10px;
  background: #eef2f5;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  border: 1px solid #e0e0e0;
}

.reply-item p {
  font-size: 0.95rem;
  color: #34495e;
  margin: 0 0 8px 0;
}

.reply-target {
  color: #409EFF;
  font-weight: bold;
  font-style: italic;
  margin-right: 5px;
}

.reply-item .comment-meta {
  font-size: 0.8rem;
}

.nested-reply {
  background: #e8f0f6;
  margin-left: 10px;
  border: 1px solid #d0e1f0;
}
</style>